package com.lm.jmh.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)// 每个线程一个独立的状态
@BenchmarkMode(Mode.AverageTime) // 测试平均耗时
@OutputTimeUnit(TimeUnit.NANOSECONDS)// 结果单位
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(0)
public class StringConcatenationBenchmark {

    private static final int ITERATIONS = 10000;

    @Benchmark
    public String testStringConcat() {
        String result = "";
        for (int i = 0; i < ITERATIONS; i++) {
            result += i; // 使用 + 拼接
        }
        return result;
    }

    @Benchmark
    public String testStringBuilder() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ITERATIONS; i++) {
            sb.append(i); // 使用 StringBuilder 拼接
        }
        return sb.toString();
    }

    // 主方法，用于运行基准测试
    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(StringConcatenationBenchmark.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}
